* =======================================================================================================================================================
*
* Code Description: 
* This codefile computes the figures provided in Table 4: Liquidity management regressions.
*
* =======================================================================================================================================================
*
* Major output:
* Table 4: Liquidity management regressions.
* =======================================================================================================================================================
*
* General disclaimer:
* This file directory produces replication code for "Connected Funds". 
* Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources, 
* we have included pseudo data to show how the raw data are formatted. 
* Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
*
* =======================================================================================================================================================


// Paths
global Path "C:\ConnectedFunds_Codebase\"
sysdir set STBPLUS "${Path}Code\Ado"   

clear all
est clear
set more off 

set scheme plottig, perm


* ============================================================== Import data into stata ================================================================


import delimited "${Path}Data\FalatoEtAl\FalatoEtAl.txt"

save "${Path}Data\FalatoEtAl\FalatoEtAl.dta", replace

clear

foreach num of numlist 1(1)128{ 
	import delimited "${Path}Data\JiangEtAl\tmp_data_`num'.txt"

	save "${Path}Data\JiangEtAl\tmp_data_`num'.dta", replace

	label define asset_type 1 "Bonds" 2 "Equities" 3 "Fund shares"
	label define asset_issovereign 0 "Non-sovereign" 1 "Sovereign"

	// Create asset class flag
	gen assetCat = ""
	
	// sovereign bonds
	replace assetCat = "GovBond" if asset_type == 1 & asset_issovereign == 1
	
	// corporate bonds
	replace assetCat = "CorpBond" if asset_type == 1 & asset_issovereign == 0
	
	// equities
	replace assetCat = "Equities" if asset_type == 2
	
	// fund shares
	replace assetCat = "FundShares" if asset_type == 3 

	collapse (sum) delta_* lag_holdings holdings holdings_lagprice (mean) datum, by(isin assetCat)
	egen lag_totalholdings 			= sum(lag_holdings), by(isin)
	egen totalholdings     			= sum(holdings), by(isin)
	egen totalholdings_lagprice     = sum(holdings_lagprice), by(isin)

	save "${Path}Data\JiangEtAl\tmp_data_AssetClass_`num'.dta", replace

	clear

}


* ================================================= Create full dataset (start with asset class data) ===================================================


clear all

use  "${Path}Data\JiangEtAl\tmp_data_AssetClass_1.dta"

foreach num of numlist 2(1)128{ 
	append using "${Path}Data\JiangEtAl\tmp_data_AssetClass_`num'.dta"
}

drop if assetCat == ""

rename delta_holdings    delta_holdings_
rename delta_holdings_price  delta_holdings_price_
rename delta_holdings_volume  delta_holdings_volume_
rename holdings  holdings_
rename lag_holdings   lag_holdings_
rename holdings_lagprice holdings_lagp_
rename lag_totalholdings lag_totalholdings_
rename totalholdings_lagprice totalholdings_lagp_

// Reshape
reshape wide delta_holdings_  delta_holdings_price_ delta_holdings_volume_  holdings_ lag_holdings_  lag_totalholdings_ holdings_lagp_  totalholdings_lagp_ , i(isin datum) j(assetCat) string

rename lag_totalholdings_CorpBond lag_totalholdings
rename totalholdings_lagp_CorpBond totalholdings_lagp
drop lag_totalholdings_* totalholdings_lagp_*

foreach l of varlist delta* lag* holdings* total* {
	replace `l' = 0 if `l' == .
}

// Save full dataset
compress

save "${Path}Data\JiangEtAl\FullData.dta", replace


* ================================================= Prepare and run liquidity management regressions ===================================================


clear all

// Load data
use "${Path}Data\JiangEtAl\FullData.dta"

merge 1:1 isin datum using "${Path}Data\FalatoEtAl\FalatoEtAl.dta"
keep if _merge == 3
drop _merge

* add vix (Source: https://www.cboe.com/tradable_products/vix/vix_historical_data/)
merge m:1 datum using "${Path}Data\VIX\VIX_monthly.dta"

keep if _merge == 3
drop _merge


* ============================================================== Preparations ==============================================================


egen ui_fund = group(isin)
egen ui_date  = group(datum)

preserve
duplicates drop datum, force
sum vixclose, det
restore

gen High_VIX = 0
replace High_VIX = 1 if vixclose >= r(p75)
replace vixclose = 0.01 * vixclose

keep if lag_holdings_FundShares > 0

sort ui_fund ui_date
xtset ui_fund ui_date

winsor2 netflows, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 returndiv, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 leverage, suffix(W) cuts(1 99) by(artmittel spezial)
gen lag_log_leverage = log(l.leverageW)

xtile tmp_pct = netflowsW, nq(5)

gen Ioutflows = 0
replace Ioutflows = 1 if netflowsW < 0

gen lag_log_tna = log(L.fondsverm)
gen log_family_tna = log(kag_tna)

gen tna     = 1000 * fondsverm
gen lag_tna = L.tna

replace bankg = 1000 * bankg
replace bankg = . if bankg < 0

gen tmp_total = bankg + totalholdings_lagp
gen tmp_lag_total = L.bankg + lag_totalholdings

gen holdings_lagp_Cash =  bankg
gen lag_holdings_Cash  =  L.bankg

tsegen netflows_sd_12m  = rowsd(L(0/11).netflowsW, 12)
gen lag_netflows_sd_12m = l.netflows_sd_12m

tsegen returndiv_sd_12m  = rowsd(L(0/11).returndivW, 12)
gen lag_returndiv_sd_12m = l.returndiv_sd_12m

drop if netflowsW == 0

global controls "lag_log_tna log_family_tna lag_log_leverage lag_netflows_sd_12m lag_returndiv_sd_12m" 

gen holdings_lagp_Total = totalholdings_lagp
gen lag_holdings_Total  = lag_totalholdings


* =================================== Run liquidity management regressions (by asset-class) ==================================================


foreach var in  "Cash" "FundShares" "Equities" "CorpBond" "GovBond" "Total" {

gen tmp2 = holdings_lagp_`var'
gen tmp1 = lag_holdings_`var'

gen perc_delta_holdings = (tmp2 - tmp1)/lag_tna
winsor2 perc_delta_holdings, suffix(W) cuts(1 99) by(artmittel spezial)

gen perc_delta_Weight = tmp2/tmp_total - tmp1/tmp_lag_total
winsor2 perc_delta_Weight, suffix(W) cuts(1 99) by(artmittel spezial)

// Institutional funds
reghdfe perc_delta_holdingsW netflowsW ${controls} if spezial == 1, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store reg_Spez_`var'_a, title(`var')

// Separately for in- and outflows
reghdfe perc_delta_holdingsW c.netflowsW##i.Ioutflows ${controls} if spezial == 1, absorb(ui_fund ui_date##artmittel) cluster(ui_date ui_fund)
est store reg_Spez_`var'_b, title(`var')

// Robustness - VIX
reghdfe perc_delta_holdingsW netflowsW ${controls} if spezial == 1 & High_VIX == 1, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store robVIX_Spez_`var'_a, title(`var')

reghdfe perc_delta_holdingsW c.netflowsW##i.Ioutflows ${controls} if spezial == 1 & High_VIX == 1, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store robVIX_Spez_`var'_b, title(`var')

// Retail funds
reghdfe perc_delta_holdingsW netflowsW ${controls} if spezial == 0, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store reg_Pub_`var'_a, title(`var')

// Separately for in- and outflows
reghdfe perc_delta_holdingsW c.netflowsW##i.Ioutflows ${controls} if spezial == 0, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store reg_Pub_`var'_b, title(`var')

// Robustness - VIX
reghdfe perc_delta_holdingsW netflowsW ${controls} if spezial == 0 & High_VIX == 1, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store robVIX_Pub_`var'_a, title(`var')

reghdfe perc_delta_holdingsW c.netflowsW##i.Ioutflows ${controls} if spezial == 0 & High_VIX == 1, absorb(ui_fund ui_date##artmittel)  cluster(ui_date ui_fund)
est store robVIX_Pub_`var'_b, title(`var')

drop *perc_delta_* tmp1 tmp2

}


* ============================================================== Export results ==============================================================


// Retail funds
esttab reg_Pub_*  using "temp.csv", drop(${controls} 0.Ioutflows) /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(r2 r2_a r2_within r2_a_within N absvars clustvar lincom_b lincom_se lincom_tval, /// 
fmt(%9.4g %9.4g  %9.4g %9.4g %16.0g %16.0g %9.4g %9.4g) ///
) nonotes noomitted mtitles label replace 

preserve
clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab4_Liquidity management regressions.xlsx", sheet("Pub")  sheetmodify   cell(B5)
restore

esttab robVIX_Pub_*  using "temp.csv", drop(${controls} 0.Ioutflows) /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(r2 r2_a r2_within r2_a_within N absvars clustvar lincom_b lincom_se lincom_tval, /// 
fmt(%9.4g %9.4g  %9.4g %9.4g %16.0g %16.0g %9.4g %9.4g) ///
) nonotes noomitted mtitles label replace 

preserve
clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab4_Liquidity management regressions.xlsx", sheet("Pub_Robustness_VIX")  sheetmodify   cell(B5)
restore


// Institutional funds
esttab reg_Spez_*  using "temp.csv", drop(${controls} 0.Ioutflows) /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(r2 r2_a r2_within r2_a_within N absvars clustvar lincom_b lincom_se lincom_tval, /// 
fmt(%9.4g %9.4g  %9.4g %9.4g %16.0g %16.0g %9.4g %9.4g) ///
) nonotes noomitted mtitles label replace 

preserve
clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab4_Liquidity management regressions.xlsx", sheet("Spezial")  sheetmodify   cell(B5)
restore

esttab robVIX_Spez_*  using "temp.csv", drop(${controls} 0.Ioutflows)  /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(r2 r2_a r2_within r2_a_within N absvars clustvar lincom_b lincom_se lincom_tval, /// 
fmt(%9.4g %9.4g  %9.4g %9.4g %16.0g %16.0g %9.4g %9.4g) ///
) nonotes noomitted mtitles label replace 

preserve
clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab4_Liquidity management regressions.xlsx", sheet("Spezial_Robustness_VIX")  sheetmodify   cell(B5)
restore